<template>
  <div class="app-container">
    <div class="filter-container filter-area">
      <!-- 修改产品类型编号为下拉选择框 -->
      <label class="filter-item" style="margin-right: 10px;">类型:</label>
      <el-select
        v-model="listQuery.prdCataCode"
        placeholder="请选择产品类型"
        clearable
        style="width: 200px;"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in productTypeOptions"
          :key="item.prdCataCode"
          :label="item.prdCataName"
          :value="item.prdCataCode"
        />
      </el-select>
      <!-- 为产品编号输入框添加标签说明 -->
      <label class="filter-item" style="margin-right: 10px;">产品编号:</label>
      <el-input
        v-model="listQuery.prodCode"
        placeholder="产品编号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <!-- 为产品名称输入框添加标签说明 -->
      <label class="filter-item" style="margin-right: 10px;">产品名称:</label>
      <el-input
        v-model="listQuery.prodName__like"
        placeholder="产品名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />

      <!-- 为状态筛选添加标签说明 -->
      <label class="filter-item" style="margin-right: 10px;">状态:</label>
      <el-select
        v-model="listQuery.sts"
        placeholder="状态"
        clearable
        style="width: 120px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option label="全部" value="" />
        <el-option
          v-for="item in statusOptions"
          :key="item.key"
          :label="item.stsDesc"
          :value="item.key"
        />
      </el-select>
    </div>

    <!-- 新增的操作按钮区 -->
    <div class="filter-container operation-area">
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 8px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加产品
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :height="tableHeight"
      :header-cell-style="{ background: '#fafafa' }"
    >
      <el-table-column label="ID" prop="id" align="center" width="100px">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型编号" min-width="60px">
        <template slot-scope="{row}">
          <span>{{ row.prdCataCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型名称" min-width="60px">
        <template slot-scope="{row}">
          <span>{{ row.prdCataName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品编号" min-width="60px">
        <template slot-scope="{row}">
          <span>{{ row.prodCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" min-width="60px">
        <template slot-scope="{row}">
          <span>{{ row.prodName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" min-width="80px">
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="150px">
        <template slot-scope="{row}">
          <span>{{ row.stsDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.sts!='1'" size="mini" type="danger" @click="handleModifyStatus(row,'1')">
            禁用
          </el-button>
          <el-button v-else size="mini" type="success" @click="handleModifyStatus(row,'0')">
            启用
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      class="pagination-container"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <!-- 修改产品类型为下拉选择框 -->
        <el-form-item label="类型" prop="prdCataCode">
          <el-select
            v-model="temp.prdCataCode"
            placeholder="请选择产品类型"
            @change="handleProductTypeChange"
          >
            <el-option
              v-for="item in productTypeOptions"
              :key="item.prdCataCode"
              :label="item.prdCataName"
              :value="item.prdCataCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品编号" prop="prodCode">
          <el-input v-model="temp.prodCode" />
        </el-form-item>
        <el-form-item label="产品名称" prop="prodName">
          <el-input v-model="temp.prodName" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="temp.remark" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="temp.sts" class="filter-item" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.key" :label="item.stsDesc" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchPrdProdList, createPrdProd, updatePrdProd, deletePrdProd, changePrdProdStatus } from '@/api/prd_prod'
import { fetchPrdCataList } from '@/api/prd_cata'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'

export default {
  name: 'PrdProd',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        enabled: 'success',
        disabled: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableHeight: 'calc(100vh - 320px)',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        prodName__like: '',
        prdCataCode: '',
        prodCode: '',
        sts: ''
      },
      temp: {
        id: undefined,
        prdCataCode: '',
        prdCataName: '',
        prodCode: '',
        prodName: '',
        remark: '',
        sts: '0',
        stsDesc: '启用'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑产品定义',
        create: '创建产品定义'
      },
      rules: {
        prdCataCode: [{ required: true, message: '产品类型不能为空', trigger: 'change' }],
        prodCode: [{ required: true, message: '产品编号不能为空', trigger: 'blur' }],
        prodName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }]
      },
      statusOptions: [
        { key: '0', stsDesc: '启用' },
        { key: '1', stsDesc: '禁用' }
      ],
      productTypeOptions: [],
      downloadLoading: false
    }
  },
  computed: {
    // 计算属性-动态计算状态下拉框的描述文本
    computedStsDesc: function() {
      const selectedOption = this.statusOptions.find(option => option.key === this.temp.sts)
      return selectedOption ? selectedOption.stsDesc : ''
    }
  },
  created() {
    console.log('Component created - calling getList and getProductTypes')
    this.getList()
    this.getProductTypes()
    this.calculateTableHeight()
    window.addEventListener('resize', this.calculateTableHeight)
  },
  mounted() {
    // Watch for DOM changes that might affect filter area height
    this.observer = new MutationObserver(this.calculateTableHeight)
    this.observer.observe(document.querySelector('.filter-area'), {
      childList: true,
      subtree: true,
      attributes: true
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeight)
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchPrdProdList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 获取产品类型列表
    getProductTypes() {
      console.log('getProductTypes method called') // Debug log
      fetchPrdCataList({ page: 1, limit: 200 }).then(response => {
        console.log('Product types response:', response) // Debug log
        this.productTypeOptions = response.data.items || []
        console.log('Product types options set:', this.productTypeOptions) // Debug log
      }).catch(error => {
        console.error('Error fetching product types:', error) // Error handling
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        prdCataCode: '',
        prdCataName: '',
        prodCode: '',
        prodName: '',
        remark: '',
        sts: '0',
        stsDesc: '启用'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 处理产品类型变化事件
    handleProductTypeChange(value) {
      const selectedType = this.productTypeOptions.find(item => item.prdCataCode === value)
      if (selectedType) {
        this.temp.prdCataName = selectedType.prdCataName
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 根据选择的产品类型代码获取对应的产品类型名称
          const selectedType = this.productTypeOptions.find(item => item.prdCataCode === this.temp.prdCataCode)
          const submitData = {
            ...this.temp,
            prdCataName: selectedType ? selectedType.prdCataName : '',
            stsDesc: this.computedStsDesc // 动态计算的状态描述文本
          }

          createPrdProd(submitData).then((response) => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '保存成功',
              message: response.data.message,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 根据选择的产品类型代码获取对应的产品类型名称
          const selectedType = this.productTypeOptions.find(item => item.prdCataCode === this.temp.prdCataCode)
          const tempData = {
            ...this.temp,
            prdCataName: selectedType ? selectedType.prdCataName : '',
            stsDesc: this.computedStsDesc // 动态计算的状态描述文本
          }
          updatePrdProd(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除该产品定义?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePrdProd(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      })
    },
    handleModifyStatus(row, status) {
      const tempData = {
        id: row.id,
        sts: status,
        stsDesc: status === '0' ? '启用' : '禁用'
      }
      changePrdProdStatus(tempData).then(() => {
        this.getList()
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '状态修改成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    calculateTableHeight() {
      const filterHeight = document.querySelector('.filter-area')?.offsetHeight || 0
      const operationHeight = document.querySelector('.operation-area')?.offsetHeight || 0
      const paginationHeight = 60
      const padding = 40

      this.tableHeight = `calc(100vh - ${filterHeight + operationHeight + paginationHeight + padding}px)`
      this.$nextTick(() => {
        this.tableKey++ // Force table re-render
      })
    }
  }
}
</script>

<style scoped>

</style>

